/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.util;

import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.dao.EntityCallback;
import cn.easyplatform.dao.IdentityDao;
import cn.easyplatform.dos.FieldDo;
import cn.easyplatform.dos.LogDo;
import cn.easyplatform.dos.UserDo;
import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.project.DeviceMapBean;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.lang.Times;
import cn.easyplatform.messages.response.LoginResponseMessage;
import cn.easyplatform.messages.vos.AgentVo;
import cn.easyplatform.messages.vos.AuthorizationVo;
import cn.easyplatform.messages.vos.RoleVo;
import cn.easyplatform.services.IProjectService;
import cn.easyplatform.support.sql.SqlParser;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.type.StateType;
import cn.easyplatform.type.UserType;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.easyplatform.dos.UserDo.STATE_ACTIVATED;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public final class IdentityUtils {

    public final static AuthorizationVo getUserAuthorization(
            final CommandContext cc, UserDo userInfo, String orgId) {
        IProjectService ps = cc.getProjectService();
        DeviceMapBean dm = ps.getDeviceMap(cc.getEnv().getPortlet(), cc
                .getEnv().getDeviceType().getName());
        IdentityDao dao = cc.getIdentityDao(false);
        EntityCallback<BaseEntity> cb = new EntityCallback<BaseEntity>() {
            @Override
            public BaseEntity getEntity(String entityId) {
                return cc.getEntity(entityId);
            }

            public String getLabel(String code) {
                return RuntimeUtils.getLabel(cc, code, userInfo.getLocale());
            }
        };
        List<RoleVo> roles = null;
        if (ps.getConfig().getStrictMode() == 1) {
            roles = dao.getUserRoles(orgId, userInfo.getId(), cc
                    .getEnv().getDeviceType().getName(), cb);
        } else {
            if (ps.getConfig().getStrictMode() == 2)
                roles = dao.getUserOrgRoles(orgId, userInfo.getId(), cc.getEnv().getDeviceType().getName(), cb);
            if (roles == null || roles.isEmpty())
                roles = dao.getUserRoles(userInfo.getId(), cc.getEnv()
                        .getDeviceType().getName(), cb);
        }
        String query = cc.getProjectService().getConfig().getUnitQuery();
        userInfo.setOrg(dao.getUserOrg(query, orgId));
        userInfo
                .getOrg()
                .setName(
                        RuntimeUtils.getLabel(cc, userInfo.getOrg()
                                .getName()));
        userInfo.setRoles(roles);
        AuthorizationVo av = new AuthorizationVo(EntityUtils.parsePage(cc,
                dm.getMainPage(), userInfo), roles);
        av.setOrgId(orgId);
        av.setOrgName(userInfo.getOrg().getName());
        query = cc.getProjectService().getConfig().getUserAgentQuery();
        if (!Strings.isBlank(query)) {
            List<AgentVo> agents = new ArrayList<AgentVo>();
            Map<String, Object> systemVariables = new HashMap<String, Object>();
            Map<String, FieldDo> userVariables = new HashMap<String, FieldDo>();
            if (userInfo.getExtraInfo() != null)
                systemVariables.putAll(userInfo.getExtraInfo());
            if (userInfo.getOrg().getExtraInfo() != null)
                systemVariables.putAll(userInfo.getOrg().getExtraInfo());
            systemVariables.put("710", cc.getEnv().getPortlet());
            systemVariables.put("720", userInfo.getId());
            systemVariables.put("722", orgId);
            systemVariables.put("728", cc.getEnv().getDeviceType()
                    .getName());
            RecordContext rc = new RecordContext(null, systemVariables,
                    userVariables);
            rc.setVariable(new FieldDo("dt", FieldType.DATE, Times.toDay()));
            SqlParser<FieldDo> parser = RuntimeUtils.createSqlParser(FieldDo.class);
            query = parser.parse(query, rc);
            List<String[]> users = dao.getAgent(query, parser.getParams());
            for (String[] user : users) {
                query = cc.getProjectService().getConfig()
                        .getUserAgentRoleQuery();
                if (Strings.isBlank(query)) {// 如果是空的，查找用户所有的角色
                    if (ps.getConfig().getStrictMode() == 1) {
                        agents.add(new AgentVo(user[0], user[1], dao
                                .getUserRoles(orgId, user[0], cc.getEnv()
                                        .getDeviceType().getName(), cb)));
                    } else {
                        List<RoleVo> ars = null;
                        if (ps.getConfig().getStrictMode() == 2) {
                            ars = dao.getUserOrgRoles(orgId, user[0], cc.getEnv()
                                    .getDeviceType().getName(), cb);
                        }
                        if (ars == null || ars.isEmpty())
                            ars = dao
                                    .getUserRoles(user[0], cc.getEnv()
                                            .getDeviceType().getName(), cb);
                        agents.add(new AgentVo(user[0], user[1], ars));
                    }
                } else {// 只查找设定的角色
                    systemVariables.put("720", user[0]);
                    parser = RuntimeUtils.createSqlParser(FieldDo.class);
                    query = parser.parse(query, rc);
                    List<RoleVo> agentRoles = dao.getRole(query,
                            parser.getParams(), cb);
                    for (RoleVo rv : agentRoles)
                        rv.setMenus(dao.getRoleMenu(rv.getId(), cc
                                .getEnv().getDeviceType().getName(), cb));
                    agents.add(new AgentVo(user[0], user[1], agentRoles));
                }
            }
            av.setAgents(agents);
        }
        userInfo.setState(StateType.START);
        cc.getSync().clear(userInfo);
        return av;
    }

    public final static void log(CommandContext cc, IdentityDao dao) {
        UserDo userInfo = cc.getUser();
        cc.login();
        if (userInfo.getType() < UserType.TYPE_OAUTH) {
            dao.updateState(userInfo.getId(), userInfo.getIp(), STATE_ACTIVATED);
            if (userInfo.getLogLevel() >= LogDo.LEVEL_USER)
                cc.getBizDao().log(
                        new LogDo(userInfo.getEventId(), userInfo.getId(), userInfo
                                .getDeviceType().getName(), LogDo.TYPE_USER,
                                "login", userInfo.getIp()));
        }
    }
}
